<template>
  <section class="content clear">
    <section class="inner-top">
      <span>接口管理</span>
    </section>
    <section class="inner-bottom">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-input type="text" v-model="interfaceName" placeholder="资源名称" size="small" clearable></el-input>
        </el-col>
        <el-col :span="4">
          <!-- <el-input type="text" v-model.number="appId" placeholder="应用编号" size="small"></el-input> -->
          <el-select v-model="appId" filterable placeholder="请选择应用" style="width:100%" clearable>
            <el-option v-for="(item,index) in allAppOptions" :key="index" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="interfaceStatus" placeholder="请选择接口状态" size="small">
            <el-option label="全部" :value="-1">
            </el-option>
            <el-option label="已启用" :value="1">
            </el-option>
            <el-option label="已禁用" :value="0">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" size="small" @click="search">搜索</el-button>
        </el-col>
        <el-col :span="8" align="right">
          <el-button type="primary" size="small" @click="addOrEditRouter('add')">添加</el-button>
        </el-col>
      </el-row>
      <el-table :data="tableData" style="width: 100%;margin-top:20px;">
        <el-table-column type="index" label="编号" width="50">
        </el-table-column>
        <el-table-column prop="name" label="名称">
        </el-table-column>
        <el-table-column prop="antPath" label="资源地址">
        </el-table-column>
        <el-table-column prop="method" label="请求方法" width="80">
        </el-table-column>
        <el-table-column prop="appName" label="应用">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
          <template slot-scope="scope">
            {{scope.row.createTime | moment('YYYY-MM-DD HH:mm:ss')}}
          </template>
        </el-table-column>
        <el-table-column prop="needControl" label="是否需要控制">
          <template slot-scope="scope">
            {{scope.row.needControl ? '是':'否'}}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="delRouter(scope.row)">删除</el-button>
            <el-button type="text" @click="addOrEditRouter('edit',scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <section class="content-page" style="margin-top:50px;">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page.current" :page-sizes="[10, 15, 20, 30]" :page-size="page.size" layout="total, sizes, prev, pager, next, jumper" :total="page.total">
        </el-pagination>
      </section>
    </section>
    <!-- 新增/编辑资源 -->
    <el-dialog :title="isAddOrEdit==='add'?'添加资源':'编辑资源'" :visible.sync="dialogVisible" width="600px" :before-close="handleClose">
      <el-form :model="interfaceForm" status-icon :rules="interfaceFromRules" ref="interfaceForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="资源名称:" prop="name">
          <el-input type="text" v-model="interfaceForm.name" autocomplete="off" size="small"></el-input>
        </el-form-item>
        <el-form-item label="资源地址:" prop="antPath">
          <el-input type="text" v-model="interfaceForm.antPath" autocomplete="off" size="small"></el-input>
        </el-form-item>
        <el-form-item label="归属应用:" prop="appId">
          <el-select v-model="interfaceForm.appId" filterable placeholder="请选择" style="width:100%">
            <el-option v-for="(item,index) in allAppOptions" :key="index" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请求方法:" prop="method">
          <el-input type="text" v-model="interfaceForm.method" autocomplete="off" size="small"></el-input>
        </el-form-item>
        <el-form-item label="权限控制" prop="needControl">
          <el-radio-group v-model="interfaceForm.needControl">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose('interfaceForm')">取 消</el-button>
        <el-button type="primary" @click="sureAddOrEditResource('interfaceForm')">确 定</el-button>
      </span>
    </el-dialog>
  </section>
</template>
<script>
import {findResourceByResourceQueryUsingPOST, createResourceUsingPOST, updateResourceUsingPUT, deleteResourceUsingDELETE, getAppAllByClassIdPOST} from '@api/systemManage'
export default {
  name: 'interfaceManage',
  data () {
    const appIdValidator = (value, rule, callback) => {
      console.log(value)
      if (value) {
        callback()
      } else {
        callback(new Error('请输入归属应用'))
      }
    }
    return {
      allAppOptions: [], // 所有应用列表
      interfaceName: null,
      appId: null,
      interfaceStatus: -1,
      tableData: [],
      isAddOrEdit: 'add', // add:新增；edit:编辑路由
      interfaceForm: {
        name: null, // 资源名称
        appId: null, // 应用id
        antPath: null, // 资源地址
        method: null, // 方法
        needControl: '0' // (1:是, 0:否)
      },
      interfaceFromRules: {
        name: [{required: true, message: '请输入资源名称', blur: 'blur'}],
        appId: [{required: true, message: '请输入归属应用', validator: appIdValidator, blur: 'blur'}], // , validator: appIdValidator
        antPath: [{required: true, message: '请输入资源地址', blur: 'blur'}],
        method: [{required: true, message: '请输入请求方法', blur: 'blur'}],
        needControl: [{required: true, message: '请选择是否需要权限控制', blur: 'blur'}]
      },
      dialogVisible: false,
      page: {
        current: 1,
        total: 0,
        size: 10
      }
    }
  },
  filters: {

  },
  created () {
    this.getAllAppList()
    this.initPage()
  },
  methods: {
    initPage () {
      let params = {
        'appId': this.appId,
        'enabled': this.interfaceStatus,
        'name': this.interfaceName,
        'page': this.page.current,
        'size': this.page.size
      }
      if (this.interfaceStatus === -1) { // 1:表示全部；不传enabled参数
        delete params.enabled
      }
      findResourceByResourceQueryUsingPOST(params).then(res => {
        if (res.status) {
          this.tableData = res.data.list
          this.page.total = res.data.total
        }
      })
    },
    filterApp (val) {
      return this.allAppOptions.find(item => {
        return item.id === val
      }).name
    },
    // 获取所有应用列表
    getAllAppList () {
      getAppAllByClassIdPOST({}).then(res => {
        if (res.status && res.data.length) {
          this.allAppOptions = res.data
        }
      })
    },
    addOrEditRouter (type = 'add', rowData = null) {
      this.isAddOrEdit = type
      this.dialogVisible = true
      if (type === 'edit') { // 编辑时赋值
        this.interfaceForm = Object.assign({}, rowData, {
          needControl: rowData.needControl ? '1' : '0'
        })
        console.log(this.interfaceForm)
      }
    },
    sureAddOrEditResource (formName) {
      this.$refs['interfaceForm'].validate(valid => {
        if (valid && this.isAddOrEdit === 'add') {
          this.addRouter()
        } else if (valid && this.isAddOrEdit === 'edit') {
          this.editRouter()
        }
      })
    },
    editRouter () {
      let params = Object.assign({}, this.interfaceForm, {
        'enabled': Boolean(Number(this.interfaceForm.enabled))
      })
      updateResourceUsingPUT(this.interfaceForm.id, params).then(res => {
        if (res.status) {
          this.initPage()
          this.handleClose()
        }
      })
    },
    addRouter () {
      let params = {
        'antPath': this.interfaceForm.antPath,
        'appId': this.interfaceForm.appId,
        'id': this.interfaceForm.id,
        'method': this.interfaceForm.method,
        'name': this.interfaceForm.name,
        'needControl': Boolean(Number(this.interfaceForm.needControl))
      }
      createResourceUsingPOST(params).then(res => {
        if (res.status) {
          this.initPage()
          this.handleClose()
        }
      })
    },
    delRouter (rowData) {
      this.$confirm('此操作将删除该资源, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteResourceUsingDELETE(rowData.id).then(res => {
          if (res.status) {
            this.$message.success('删除成功')
            this.initPage()
          }
        })
      }).catch(() => {

      })
    },
    handleClose () {
      this.$refs['interfaceForm'].resetFields()
      this.$refs['interfaceForm'].clearValidate()
      this.dialogVisible = false
    },
    search () {
      this.page.current = 1
      this.initPage()
    },
    handleSizeChange (val) {
      this.page.size = val
      this.initPage()
    },
    handleCurrentChange (val) {
      this.page.current = val
      this.initPage()
    }
  }
}
</script>
